{% extends "base.html" %}

{% block title %}{{ room.name }} - SteHub{% endblock %}

{% block extra_css %}
<style>
.chat-container {
    height: 70vh;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
}
.chat-sidebar {
    width: 300px;
    background: #f8f9fa;
    border-right: 1px solid #dee2e6;
    display: flex;
    flex-direction: column;
}
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
}
.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
    background: white;
}
.chat-input-area {
    border-top: 1px solid #dee2e6;
    padding: 1rem;
    background: #f8f9fa;
}
.message {
    margin-bottom: 1rem;
    padding: 0.5rem 1rem;
    border-radius: 8px;
    max-width: 80%;
}
.message.own {
    background: #007bff;
    color: white;
    margin-left: auto;
}
.message.other {
    background: #e9ecef;
    color: #333;
}
.message-system {
    background: #fff3cd;
    color: #856404;
    text-align: center;
    max-width: 100%;
    font-style: italic;
}
.message-header {
    font-size: 0.8rem;
    margin-bottom: 0.25rem;
    opacity: 0.8;
}
.message-content {
    word-wrap: break-word;
}
.member-list {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}
.member-item {
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    margin-bottom: 0.5rem;
}
.member-item:hover {
    background: #e9ecef;
}
.online-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #28a745;
    margin-right: 0.5rem;
}
.typing-indicator {
    font-style: italic;
    color: #6c757d;
    padding: 0.5rem 1rem;
}
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- 聊天室头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="mb-1">{{ room.name }}</h2>
                <p class="text-muted mb-0">{{ room.description or '暂无描述' }}</p>
            </div>
            <div class="d-flex align-items-center">
                <span class="badge bg-primary me-3">
                    <i class="fas fa-users me-1"></i>{{ room.member_count }} 成员
                </span>
                {% if room in current_user.joined_rooms or current_user.is_admin %}
                <form method="POST" action="{{ url_for('chat.leave_room', room_id=room.id) }}" 
                      class="d-inline leave-room-form">
                    <button type="submit" class="btn btn-outline-danger">
                        <i class="fas fa-sign-out-alt me-2"></i>离开房间
                    </button>
                </form>
                {% else %}
                <form method="POST" action="{{ url_for('chat.join_room', room_id=room.id) }}" 
                      class="d-inline join-room-form">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i>加入房间
                    </button>
                </form>
                {% endif %}
            </div>
        </div>

        <!-- 聊天容器 -->
        <div class="chat-container">
            <!-- 侧边栏 - 成员列表 -->
            <div class="chat-sidebar">
                <div class="p-3 border-bottom">
                    <h6 class="mb-0">房间成员</h6>
                </div>
                <div class="member-list">
                    {% for member in members %}
                    <div class="member-item">
                        <span class="online-indicator"></span>
                        <div class="flex-grow-1">
                            <strong>{{ member.username }}</strong>
                            {% if member.id == room.created_by %}
                            <small class="text-warning ms-1">(创建者)</small>
                            {% endif %}
                        </div>
                        {% if current_user.is_authenticated and current_user.id != member.id %}
                        <a href="{{ url_for('chat.private_chat', user_id=member.id) }}" 
                           class="btn btn-sm btn-outline-primary" title="私聊">
                            <i class="fas fa-comment"></i>
                        </a>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
                <div class="p-3 border-top">
                    <small class="text-muted">
                        {% if room.is_public %}
                        <i class="fas fa-globe me-1"></i>公共房间
                        {% else %}
                        <i class="fas fa-lock me-1"></i>私有房间
                        {% endif %}
                    </small>
                </div>
            </div>

            <!-- 主聊天区域 -->
            <div class="chat-main">
                <!-- 消息区域 -->
                <div class="chat-messages" id="chatMessages">
                    {% if messages %}
                        {% for message in messages %}
                        <div class="message {% if message.author_id == current_user.id %}own{% else %}other{% endif %}">
                            <div class="message-header">
                                <strong>{{ message.author.username }}</strong>
                                <small>{{ message.created_at|format_timestamp('%H:%M') }}</small>
                            </div>
                            <div class="message-content">
                                {{ message.content }}
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-comments fa-3x mb-3"></i>
                            <p>还没有消息，开始聊天吧！</p>
                        </div>
                    {% endif %}
                    <div id="typingIndicator" class="typing-indicator d-none"></div>
                </div>

                <!-- 输入区域 -->
                {% if room in current_user.joined_rooms or current_user.is_admin %}
                <div class="chat-input-area">
                    <form id="messageForm" class="d-flex">
                        <input type="text" id="messageInput" class="form-control me-2" 
                               placeholder="输入消息..." maxlength="1000" autocomplete="off">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </form>
                    <div class="mt-2">
                        <small class="text-muted">
                            按 Enter 发送，Shift + Enter 换行
                        </small>
                    </div>
                </div>
                {% else %}
                <div class="chat-input-area text-center py-4">
                    <p class="text-muted">请先加入房间才能发送消息</p>
                    <form method="POST" action="{{ url_for('chat.join_room', room_id=room.id) }}" 
                          class="d-inline join-room-form">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>加入房间
                        </button>
                    </form>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatMessages = document.getElementById('chatMessages');
    const messageForm = document.getElementById('messageForm');
    const messageInput = document.getElementById('messageInput');
    const typingIndicator = document.getElementById('typingIndicator');
    
    let socket;
    let typingTimer;

    // 初始化Socket.IO连接
    if (typeof io !== 'undefined') {
        socket = io();
        
        // 加入房间
        socket.emit('join_room', { room_id: {{ room.id }} });
        
        // 监听新消息
        socket.on('new_message', function(data) {
            addMessageToChat(data);
            scrollToBottom();
        });
        
        // 监听用户加入
        socket.on('user_joined', function(data) {
            addSystemMessage(`${data.username} 加入了房间`);
        });
        
        // 监听用户离开
        socket.on('user_left', function(data) {
            addSystemMessage(`${data.username} 离开了房间`);
        });
        
        // 监听输入状态
        socket.on('user_typing', function(data) {
            showTypingIndicator(data.username);
        });
        
        socket.on('user_stop_typing', function(data) {
            hideTypingIndicator();
        });
    }

    // 添加消息到聊天区域
    function addMessageToChat(data) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${data.is_own ? 'own' : 'other'}`;
        
        messageDiv.innerHTML = `
            <div class="message-header">
                <strong>${data.author.username}</strong>
                <small>${new Date().toLocaleTimeString()}</small>
            </div>
            <div class="message-content">
                ${data.content}
            </div>
        `;
        
        chatMessages.appendChild(messageDiv);
    }

    // 添加系统消息
    function addSystemMessage(content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message message-system';
        messageDiv.textContent = content;
        
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
    }

    // 滚动到底部
    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 显示输入指示器
    function showTypingIndicator(username) {
        typingIndicator.textContent = `${username} 正在输入...`;
        typingIndicator.classList.remove('d-none');
        scrollToBottom();
    }

    // 隐藏输入指示器
    function hideTypingIndicator() {
        typingIndicator.classList.add('d-none');
    }

    // 消息表单提交
    if (messageForm) {
        messageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const content = messageInput.value.trim();
            if (content) {
                // 发送消息
                socket.emit('send_message', {
                    room_id: {{ room.id }},
                    content: content
                });
                
                // 清空输入框
                messageInput.value = '';
                
                // 停止输入状态
                socket.emit('stop_typing', { room_id: {{ room.id }} });
            }
        });
    }

    // 输入框事件
    if (messageInput) {
        messageInput.addEventListener('input', function() {
            if (this.value.trim()) {
                socket.emit('typing', { room_id: {{ room.id }} });
                
                clearTimeout(typingTimer);
                typingTimer = setTimeout(() => {
                    socket.emit('stop_typing', { room_id: {{ room.id }} });
                }, 1000);
            }
        });
        
        // 键盘快捷键
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                messageForm.dispatchEvent(new Event('submit'));
            }
        });
    }

    // 离开房间表单
    const leaveRoomForm = document.querySelector('.leave-room-form');
    if (leaveRoomForm) {
        leaveRoomForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (confirm('确定要离开这个聊天室吗？')) {
                fetch(this.action, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (data.redirect_url) {
                            window.location.href = data.redirect_url;
                        } else {
                            window.location.href = "{{ url_for('chat.index') }}";
                        }
                    } else {
                        alert('离开失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('离开失败');
                });
            }
        });
    }

    // 加入房间表单
    const joinRoomForm = document.querySelector('.join-room-form');
    if (joinRoomForm) {
        joinRoomForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            fetch(this.action, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('加入失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('加入失败');
            });
        });
    }

    // 初始滚动到底部
    scrollToBottom();
});
</script>
{% endblock %}